/*
 * @lc app=leetcode.cn id=2 lang=golang
 *
 * [2] 两数相加
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
	var carry int = 0

	var head *ListNode
	var pn *ListNode

	for l1 != nil || l2 != nil {
		var s int = carry
		if l1 != nil {
			s += l1.Val
			l1 = l1.Next
		}
		if l2 != nil {
			s += l2.Val
			l2 = l2.Next
		}
		carry = s / 10
		s = s % 10
		var n *ListNode = &ListNode{s, nil}
		if head == nil {
			head = n
			pn = n
		} else {
			pn.Next = n
			pn = pn.Next
		}
	}

	if carry > 0 {
		pn.Next = &ListNode{1, nil}
	}

	return head
}

// @lc code=end

